package com.roncoo.education.oauth.point;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.roncoo.education.course.feign.interfaces.score.constant.UploadScoreCodeConst;

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint
{
 
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = authException.getCause();
 
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            JSONObject jsonObject = new JSONObject();
            if (cause instanceof InvalidTokenException) {
//                response.getWriter().write(ResultJsonUtil.build(
//                        0,    // 请求失败
//                        2001, // token 失效
//                        "token 格式非法或已失效"
//                ));

                jsonObject.put("code", UploadScoreCodeConst.code_5);
                jsonObject.put("msg", UploadScoreCodeConst.code_5_msg);
            } else if (authException instanceof InsufficientAuthenticationException) {
                jsonObject.put("code", UploadScoreCodeConst.code_999);
                jsonObject.put("msg", cause.getMessage());            	
            } else {
//                response.getWriter().write(ResultJsonUtil.build(
//                        0,   // 请求失败
//                        2008,// token 缺失
//                        "token 缺失"
//                ));

                jsonObject.put("code", UploadScoreCodeConst.code_1);
                jsonObject.put("msg", UploadScoreCodeConst.code_1_msg);
            }
            response.getWriter().write(JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
